package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.tool.api.R;
import com.guodi.map.entity.MapDataProject;
import com.guodi.map.service.IMapDataProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;


/**
 * @描述：专题图制作-数据产品表控制类
 * @作者: 代鹏刚
 * @日期: 2020-07-10
 */
@RestController
@RequestMapping("/MapDataProject")
@Api(value = "API - MapDataProjectController", tags = "专题图制作-数据产品表")
public class MapDataProjectController extends BaseController {

    @Autowired
    public IMapDataProjectService mapDataProjectService;

    /**
    * @描述: 根据实体属性分页查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020-07-10
    **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页索引", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面记录大小", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "creator", value = "创建人ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认(1:是 0:否)", dataType = "string", paramType = "query")
    })
    public R listByEntity(@ApiIgnore Page page, @ApiIgnore MapDataProject mapDataProject){
        LambdaQueryWrapper<MapDataProject> wrapper = new QueryWrapper().lambda();
        if(StringUtils.isNotBlank(mapDataProject.getIsDefault())) {
            wrapper.eq(MapDataProject::getIsDefault, "1").or().eq(MapDataProject::getCreator, mapDataProject.getCreator());
        }else{
            wrapper.eq(MapDataProject::getCreator,mapDataProject.getCreator());
        }
        IPage<MapDataProject> iPage = mapDataProjectService.page(page, wrapper);
        return R.data(iPage);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-07-10
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapDataProject mapDataProject = mapDataProjectService.getById(id);
        return R.data(mapDataProject);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-07-10
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "地图名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "unit", value = "制作单位", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "fileSize", value = "文件尺寸(A3、A4)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "layout", value = "布局(横向、纵向)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "fileType", value = "文件格式", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "resolution", value = "分辨率", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "fileUrl", value = "专题图地址", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认(1:是 0:否)", required = true, dataType = "string", paramType = "query")
    })
    public R save(@ApiIgnore MapDataProject mapDataProject)throws Exception {
        prepareData(mapDataProject, true);
        mapDataProject.setId(UuidUtil.get32UUID());
        //将专题图上传至FTP服务器
        URL url = new URL(mapDataProject.getFileUrl());
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        /*ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int rc = 0;
        while ((rc = inputStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] bytes = swapStream.toByteArray();*/
        String fileUrl = MinioUtil.uploadFile(inputStream, "Map-Data-Projrct", mapDataProject.getName()+"."+mapDataProject.getFileType());
        mapDataProject.setFileUrl(fileUrl);
        return R.status(mapDataProjectService.save(mapDataProject));
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-07-10
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapDataProject mapDataProject) {
        prepareData(mapDataProject, false);
        return R.status(mapDataProjectService.updateById(mapDataProject));
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020-07-10
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R delete(String id){
        MapDataProject mapDataProject = mapDataProjectService.getById(id);
        //删除FDFS文件
        if (StringUtils.isNotBlank(mapDataProject.getFileUrl())) {
            MinioUtil.removeFile(mapDataProject.getFileUrl());
        }
        mapDataProjectService.removeById(id);
        return new R();
    }


    private void prepareData(MapDataProject mapDataProject, boolean isSave) {
        if(isSave){
            mapDataProject.setCreator(getUser().getUserId().toString());
            mapDataProject.setCreateTime(new Date());
            //防止误修改
            mapDataProject.setModifier(null);
            mapDataProject.setModifyTime(null);
        }else{
            mapDataProject.setModifier(getUser().getUserId().toString());
            mapDataProject.setModifyTime(new Date());
            //防止误修改
            mapDataProject.setCreator(null);
            mapDataProject.setCreateTime(null);
        }
    }
}
